package com.jfinal.enjoy.parser

import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.PsiTreeUtil
import com.jfinal.enjoy.EnjoySyntaxHighlighter
import com.jfinal.enjoy.psi.EnjoyTypes

class EnjoyIfAnnotator : Annotator {
    override fun annotate(element: PsiElement, holder: AnnotationHolder) {
        // 只处理 IF 指令的 PSI 节点
        if (element.node.elementType == EnjoyTypes.IF_DIRECTIVE) {
            val lparen = element.findChildByType(EnjoyTypes.LPAREN)
            val rparen = element.findChildByType(EnjoyTypes.RPAREN)

            // 高亮 #if 部分
            val hashToken = element.firstChild
            if (hashToken != null) {
                holder.newSilentAnnotation(HighlightSeverity.INFORMATION)
                    .range(hashToken.textRange)
                    .textAttributes(EnjoySyntaxHighlighter.KEYWORD) // 你的关键字样式
                    .create()
            }

            // 检测缺失右括号
            if (lparen != null && rparen == null) {
                holder.newAnnotation(HighlightSeverity.ERROR, "#if 缺少闭括号")
                    .range(lparen.textRange)
                    .create()
            }
        }
    }

    fun PsiElement.findChildByType(type: IElementType): PsiElement? {
        return PsiTreeUtil.findChildrenOfType(this, LeafPsiElement::class.java)
            .firstOrNull { it.node.elementType == type }
    }
}